<template>
  <ElDrawer
    v-model="drawerVisible"
    :title="title"
    :size="size"
    :destroy-on-close="destroyOnClose"
    :append-to-body="appendToBody"
    :close-on-click-modal="closeOnClickModal"
    :open-delay="openDelay"
    :close-delay="closeDelay"
    :with-header="withHeader"
    :show-close="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <template #header>
      <slot name="header">
        <div style="position: relative; height: 10px">
          <slot name="title">{{ title }}</slot>
          <div style="position: absolute; top: 0; right: 0; cursor: pointer">
            <span class="header-btn">
              <ElIcon @click="close" size="20px"><Close /></ElIcon>
            </span>
          </div>
        </div>
      </slot>
    </template>
    <slot></slot>
    <template #footer>
      <slot name="footer">
        <slot name="beforeFooter" />
        <ElButton @click="handleCancel"> {{ cancelText }} </ElButton>
        <ElButton type="primary" @click="handleSubmit" v-loading="loading"> {{ submitText }} </ElButton>
        <slot name="afterFooter" />
      </slot>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts" name="Drawer">
import { ref } from "vue";
import { ElDrawer, ElIcon, ElButton } from "element-plus";
import { Close } from "@element-plus/icons-vue";
defineProps({
  title: {
    type: String
  },
  size: {
    type: String
  },
  appendToBody: {
    type: Boolean,
    default: true
  },
  destroyOnClose: {
    type: Boolean,
    default: true
  },
  closeOnClickModal: {
    type: Boolean,
    default: false
  },
  withHeader: {
    type: Boolean,
    default: true
  },
  openDelay: {
    type: Number
  },
  closeDelay: {
    type: Number
  },
  cancelText: {
    type: String,
    default: "取消"
  },
  submitText: {
    type: String,
    default: "确认"
  }
});
const emit = defineEmits(["close", "submit", "open"]);
const drawerVisible = ref(false);
const loading = ref(false);
const openFlag = ref(false);
const flagRef = ref();
const open = (flag?: any) => {
  flagRef.value = flag;
  drawerVisible.value = true;
};
const close = () => {
  drawerVisible.value = false;
};

const handleClose = () => {
  close();
};

const handleOpen = () => {
  if (!openFlag.value) {
    openFlag.value = true;
    emit("open");
  }
};

const handleCancel = () => {
  close();
};
const openLoading = async (callback: () => void) => {
  loading.value = true;
  try {
    await callback();
  } finally {
    loading.value = false;
  }
};
const handleSubmit = () => {
  emit("submit", flagRef.value);
};
defineExpose({ open, close, openLoading });
</script>
<style scoped>
.header-btn {
  margin-left: 10px;
}
</style>
